package cn.sirun.com.fca.personal.center.model.service;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.PublishSubject;

/**
 * @author showxiao
 * @date 2018/8/16
 */
public class PinCodeManager {

    private static volatile PinCodeManager sInstance;

    public static PinCodeManager getInstance() {
        if (sInstance == null) {
            synchronized (PinCodeManager.class) {
                if (sInstance == null) {
                    sInstance = new PinCodeManager();
                }
            }
        }
        return sInstance;
    }

    public static void destroy() {
        if (sInstance != null) {
            synchronized (PinCodeManager.class) {
                if (sInstance != null) {
                    sInstance.onDestroy();
                    sInstance = null;
                }
            }
        }
    }

    private PublishSubject<Boolean> mPinCodeSubject;
    private Disposable mDisposable;

    private PinCodeManager() {
        mPinCodeSubject = PublishSubject.create();
    }

    public Observable<Boolean> getPinCodeVerificationObservable() {
        return mPinCodeSubject.firstOrError().toObservable();
    }

    public void emitPinCodeVerificationResult(boolean verified) {
        mPinCodeSubject.onNext(verified);
    }

    private void onDestroy() {
        if (mDisposable != null) {
            mDisposable.dispose();
            mDisposable = null;
        }
        mPinCodeSubject = null;
    }
}
